package dish

import (
	"context"
	"encoding/json"
	"github.com/google/uuid"
	"insighttracking/apps/customer/auth"
	"insighttracking/apps/customer/internal/types"
	"insighttracking/common/utils"
	"insighttracking/query/service"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
	"insighttracking/apps/customer/internal/svc"
	"os"
)

type DishesApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewDishApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *DishesApiLogic {
	hostname, _ := os.Hostname()
	return &DishesApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *DishesApiLogic) GetListApi(req *types.DishListReq) (resp *types.DishListResp, err error) {
	resp = &types.DishListResp{}
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}
	date := utils.DateStrToTime(req.Date)
	entities, err := service.MealService.GetCustomerMealApi(l.ctx, accountInfo.CustomerId, date, req.Type)
	if err != nil {
		return
	}
	var dishIDs []int64
	for _, entity := range entities {
		var ids []int64
		err = json.Unmarshal([]byte(entity.DishesIds), &ids)
		if err != nil {
			return
		}
		dishIDs = append(dishIDs, ids...)
	}

	dishIDDataMap, err := service.DishService.GetDishInfoMapApi(l.ctx, dishIDs)
	list := make([]*types.DishList, 0)
	for _, dish := range dishIDDataMap {
		list = append(list, &types.DishList{
			ID:         dish.ID,
			Image:      dish.Image,
			Name:       dish.Name,
			SalesPrice: dish.SalesPrice,
		})
	}
	resp.List = list
	return
}

func (l *DishesApiLogic) GetDetailApi(req *types.IdReq) (resp *types.DishDetailResp, err error) {
	resp = &types.DishDetailResp{}
	dish, err := service.DishService.GetByIDApi(l.ctx, req.Id)
	if err != nil {
		return
	}
	resp.Describe = dish.Describe
	resp.Name = dish.Name
	resp.Image = dish.Image
	resp.SalesPrice = dish.SalesPrice
	resp.Id = dish.ID
	spuRatioInfo, err := service.DishService.GetSpuRatioApi(l.ctx, req.Id)
	if err != nil {
		return
	}
	resp.SpuRatioInfo = spuRatioInfo
	return
}
